package com.ykdl.member.kid.sqlite;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
/**
 * 记录登录状态，cooket，同步数据结果，新功能展示的表
 */
public class LogonCookeDao extends AbstractDB {

	public LogonCookeDao(Context context) {
		super(context);
	}

	public static final String TABLE_NAME = "logonstate";

	public String getTableName() {
		return TABLE_NAME;
	}

	public static final String ROWID = "rowid";

	public static final String LOGONSTR = "logonstr";
	public static final String COOKET = "cooket";
	public static final String SYNCDATA = "syncdata";
	public static final String WELCOME = "welcome";

	public static final String create_table = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" + //
			ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT," + // 0
			LOGONSTR + " TEXT," + // 1
			COOKET + " TEXT," + // 2
			SYNCDATA + " TEXT," + // 3
			WELCOME + " TEXT" + // 4
			")";

	public void insertData(LogonRect data) {
		LogonRect bean = fetchAllData();
		if (bean.isAnonymous.length() > 0 || bean.cooket.length() > 0 || bean.syncdata.length() > 0
				|| bean.welcome.length() > 0) {
			updateData("1", data);
		} else {
			ContentValues cv = bean2ContentValue(data);
			insert(TABLE_NAME, null, cv);
		}
	}

	private void updateData(String id, LogonRect data) {
		ContentValues cv = bean2ContentValue(data);
		update(TABLE_NAME, cv, ROWID + "='" + id + "'", null);
	}

	public LogonRect fetchAllData() {
		checkDbOpen();
		String QUERY = "SELECT * from " + TABLE_NAME;
		Cursor cursor;
		try {
			cursor = query(QUERY, null);
		} catch (java.lang.IllegalStateException ee) {
			cursor = query(QUERY, null);
		}
		LogonRect bean = new LogonRect();
		while (cursor.moveToNext()) {
			bean.isAnonymous = cursor.getString(1);
			bean.cooket = cursor.getString(2);
			bean.syncdata = cursor.getString(3);
			bean.welcome = cursor.getString(4);
		}
		cursor.close();
		close();
		return bean;
	}

	private ContentValues bean2ContentValue(LogonRect data) {
		ContentValues cvalues = new ContentValues();
		// LOGONSTR + " TEXT," + // 1
		// COOKET + " TEXT," + // 2
		// SYNCDATA + " TEXT," + // 3
		// WELCOME + " TEXT" + // 4

		cvalues.put(LOGONSTR, data.isAnonymous);
		cvalues.put(COOKET, data.cooket);
		cvalues.put(SYNCDATA, data.syncdata);
		cvalues.put(WELCOME, data.welcome);

		return cvalues;
	}

}
